package com.atguigu.lease.web.app.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.context.LoginUserContext;
import com.atguigu.lease.web.app.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.校验获取用户的token
        String token = request.getHeader("access_token");

        //2.解析token
        if(!StringUtils.hasLength(token)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }

        Long userId = JwtUtil.parseToken(token);
        UserInfo userInfo = userInfoService.getById(userId);
        userInfo.setPassword(null);

        //将数据共享
        LoginUserContext.setUser(userInfo);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.removeUser();
    }
}
